from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (QTableWidget,
                             QTableWidgetItem, QWidget, QPushButton, QVBoxLayout, QDialog, QFormLayout, QLineEdit,
                             QHBoxLayout, QFileDialog, QComboBox, QTextEdit, QLabel, QMessageBox, QHeaderView)
from src.backend.tools.file import parser_html
from src.backend.datafactory import topic_level, topic_category
from src.backend.service.knowledge import recognize
from src.forward.base.RightWidget import RightWidget
from src.forward.base.bean import forward, Table_ABC
from PyQt5.QtCore import Qt, QDate

@forward(name='问题提取')
class TestPaper(RightWidget):

    def __init__(self):
        super().__init__()
        self.paper_layout=QVBoxLayout()
        # self.paper_layout.setContentsMargins(0,10,0,self.height()-100)
        ## 查询控件
        operator=QWidget()
        operator_layout=QHBoxLayout()
        operator.setLayout(operator_layout)
        operator.setLayout(operator_layout)

        single=QWidget()
        single_layout=QHBoxLayout()
        from src.forward.base.bean import CustomTextEdit
        from src.backend.beanfactory import BeanFactory
        path=BeanFactory.getCursor().image_path
        self.textedit=CustomTextEdit(path)
        self.textedit.setPlaceholderText('''输入题目信息，比如:
1.已知正数a，b满足，则（　　）
A．a＞b2	B．a＜b2	C．a＞2b	D．a＜2b。
可复制黏贴，阿拉伯数字排列''')

        # lineedit=QLineEdit('输入考察的内容')
        single_layout.addWidget(self.textedit)
        sub=QPushButton('切题')
        sub.clicked.connect(self.submit)
        sql_button = QPushButton('入库')
        sql_button.clicked.connect(self.insert_sqlite)
        # single_layout.addWidget(com)
        single_layout.addWidget(sub)
        single_layout.addWidget(sql_button)
        single.setLayout(single_layout)
        self.knowledge = Table_ABC()
        self.labels = ['内容', '考点', '模块', '答案', '难易等级', '类型', '分数', '方法', '最佳方法']
        self.knowledge.setColumnCount(len(self.labels))
        self.knowledge.setHorizontalHeaderLabels(self.labels)
        # self.knowledge.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        self.knowledge.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)

        self.paper_layout.addWidget(operator)
        self.paper_layout.addWidget(single)
        self.paper_layout.addWidget(self.knowledge)
        self.setLayout(self.paper_layout)

    def insert_sqlite(self):
        data=self.knowledge.get_data()
        from src.backend.api.testpaper import topic_insert_sqlite
        topic_insert_sqlite(data)
        QMessageBox.information(self, "成功", "入库完成")

    def cut_theme(self):
        '''
        切题
        :return:
        '''
        if self.file_input.split('.')[-1] in ['doc','docx','pdf']:
            tables=recognize(self.file_input)
        else:
            pass

    def fill_data(self):
        '''
        填充数据
        :param data:
        :return:
        '''
        pass


    def file(self):
        # 打开文件对话框，让用户选择文件
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_name, _ = QFileDialog.getOpenFileName(self, "选择文件", "", "所有文件 (*);;Python Files (*.py)", options=options)
        self.file_input.setText(file_name)
        self.file_input.setVisible(True)

    def submit(self):
        html=self.textedit.toHtml()
        questions=parser_html(html)

        # 插入足够的行数
        self.knowledge.setRowCount(len(questions))
        # content, examinations, modules,
        # answer, level, category, score, methods, method
        for row, p in enumerate(questions):
            for col in range(len(self.labels)):
                if col==self.labels.index('难易等级'):
                    text=QComboBox()
                    text.addItems(topic_level().values[:,0])
                elif col==self.labels.index('类型'):
                    text=QComboBox()
                    text.addItems(topic_category().values[:,0])
                elif col==2 or col==3:
                    text=QLineEdit()
                else:
                    text = QTextEdit()
                self.knowledge.setCellWidget(row, col, text)
                if col == 0:
                    text.setHtml(str(p))
                    text.setReadOnly(True)
        # 手动设置所有行的高度
        for row in range(self.knowledge.rowCount()):
            self.knowledge.setRowHeight(row, 100)  # 设置每行高度为50像素
        # 自动调整所有列的宽度
        self.knowledge.resizeColumnsToContents()
        self.knowledge.resizeRowsToContents()


